import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 模拟门诊缴费数据
const mockBills = [
  {
    id: 'B001',
    patientName: '王*柯',
    department: '内科',
    doctorName: '张医生',
    billDate: '2024-01-15',
    billType: '门诊挂号费',
    amount: 50,
    status: '待缴费',
    billNo: '20240115001',
    paymentMethod: null,
    paymentTime: null
  },
  {
    id: 'B002',
    patientName: '王*柯',
    department: '外科',
    doctorName: '李医生',
    billDate: '2024-01-20',
    billType: '检查费',
    amount: 120,
    status: '待缴费',
    billNo: '20240120001',
    paymentMethod: null,
    paymentTime: null
  },
  {
    id: 'B003',
    patientName: '王*柯',
    department: '儿科',
    doctorName: '王医生',
    billDate: '2024-01-25',
    billType: '药品费',
    amount: 85,
    status: '已缴费',
    billNo: '20240125001',
    paymentMethod: '微信支付',
    paymentTime: '2024-01-25 10:30:00'
  }
]

// 异步thunk
export const fetchBills = createAsyncThunk(
  'payment/fetchBills',
  async () => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return mockBills
  }
)

export const payBill = createAsyncThunk(
  'payment/payBill',
  async (paymentData) => {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟支付结果
    const success = Math.random() > 0.1 // 90%成功率
    
    if (success) {
      return {
        billId: paymentData.billId,
        paymentMethod: paymentData.paymentMethod,
        paymentTime: new Date().toISOString(),
        transactionId: `TXN${Date.now()}`,
        success: true
      }
    } else {
      throw new Error('支付失败，请重试')
    }
  }
)

export const getBillDetail = createAsyncThunk(
  'payment/getBillDetail',
  async (billId) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    const bill = mockBills.find(b => b.id === billId)
    if (!bill) {
      throw new Error('账单不存在')
    }
    return bill
  }
)

// 初始状态
const initialState = {
  bills: [],
  currentBill: null,
  loading: false,
  error: null,
  paymentLoading: false
}

// 创建slice
const paymentSlice = createSlice({
  name: 'payment',
  initialState,
  reducers: {
    // 添加新账单
    addBill: (state, action) => {
      state.bills.unshift(action.payload)
    },
    // 更新账单状态
    updateBillStatus: (state, action) => {
      const { billId, status, paymentMethod, paymentTime } = action.payload
      const bill = state.bills.find(b => b.id === billId)
      if (bill) {
        bill.status = status
        if (paymentMethod) bill.paymentMethod = paymentMethod
        if (paymentTime) bill.paymentTime = paymentTime
      }
    },
    // 设置当前查看的账单
    setCurrentBill: (state, action) => {
      state.currentBill = action.payload
    },
    // 清除当前账单
    clearCurrentBill: (state) => {
      state.currentBill = null
    },
    // 清除错误
    clearError: (state) => {
      state.error = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取账单列表
      .addCase(fetchBills.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchBills.fulfilled, (state, action) => {
        state.loading = false
        state.bills = action.payload
      })
      .addCase(fetchBills.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 支付账单
      .addCase(payBill.pending, (state) => {
        state.paymentLoading = true
        state.error = null
      })
      .addCase(payBill.fulfilled, (state, action) => {
        state.paymentLoading = false
        // 更新账单状态
        const bill = state.bills.find(b => b.id === action.payload.billId)
        if (bill) {
          bill.status = '已缴费'
          bill.paymentMethod = action.payload.paymentMethod
          bill.paymentTime = action.payload.paymentTime
        }
      })
      .addCase(payBill.rejected, (state, action) => {
        state.paymentLoading = false
        state.error = action.error.message
      })
      // 获取账单详情
      .addCase(getBillDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(getBillDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentBill = action.payload
      })
      .addCase(getBillDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
  }
})

// 导出actions
export const {
  addBill,
  updateBillStatus,
  setCurrentBill,
  clearCurrentBill,
  clearError
} = paymentSlice.actions

// 导出selectors
export const selectBills = (state) => state.payment.bills
export const selectCurrentBill = (state) => state.payment.currentBill
export const selectPaymentLoading = (state) => state.payment.loading
export const selectPaymentError = (state) => state.payment.error
export const selectPaymentProcessing = (state) => state.payment.paymentLoading

// 导出计算属性selectors
export const selectPendingBills = (state) => 
  state.payment.bills.filter(bill => bill.status === '待缴费')

export const selectPaidBills = (state) => 
  state.payment.bills.filter(bill => bill.status === '已缴费')

export const selectTotalPendingAmount = (state) => 
  state.payment.bills
    .filter(bill => bill.status === '待缴费')
    .reduce((total, bill) => total + bill.amount, 0)

// 导出reducer
export default paymentSlice.reducer
